// 模块开关配置组件 - 基于用户需求说明2.1.8.8

import React, { useState } from 'react';
import { useHmiState } from '../hooks/useHmiState';
import {
  Power,
  Camera,
  Radar,
  MapPin,
  Eye,
  Cpu,
  Car,
  Settings,
  AlertTriangle,
  CheckCircle,
  XCircle,
  WifiOff
} from 'lucide-react';

const ModuleControlPanel: React.FC = () => {
  const { userRole, vehicleStatus, moduleStatus } = useHmiState();
  const [moduleStates, setModuleStates] = useState({
    autonomousMode: vehicleStatus.autonomousMode,
    camera: true,
    lidar: true,
    radar: true,
    gps: true,
    imu: true,
    perception: true,
    planning: true,
    control: true,
    chassis: true
  });
  const [showConfirmDialog, setShowConfirmDialog] = useState<string | null>(null);

  // 乘客模式下隐藏模块开关配置面板
  if (userRole.type === 'passenger') {
    return null;
  }

  const modules = [
    {
      id: 'camera',
      name: '摄像头',
      description: '视觉感知系统',
      icon: <Camera size={20} />,
      critical: true
    },
    {
      id: 'lidar',
      name: '激光雷达',
      description: '3D点云感知',
      icon: <Radar size={20} />,
      critical: true
    },
    {
      id: 'radar',
      name: '毫米波雷达',
      description: '距离和速度检测',
      icon: <Radar size={20} />,
      critical: true
    },
    {
      id: 'gps',
      name: 'GPS定位',
      description: '全球定位系统',
      icon: <MapPin size={20} />,
      critical: true
    },
    {
      id: 'imu',
      name: '惯性测量单元',
      description: '姿态和加速度',
      icon: <Settings size={20} />,
      critical: true
    },
    {
      id: 'perception',
      name: '感知模块',
      description: '目标检测和跟踪',
      icon: <Eye size={20} />,
      critical: true
    },
    {
      id: 'planning',
      name: '规划模块',
      description: '路径规划',
      icon: <Cpu size={20} />,
      critical: true
    },
    {
      id: 'control',
      name: '控制模块',
      description: '车辆控制',
      icon: <Car size={20} />,
      critical: true
    },
    {
      id: 'chassis',
      name: '底盘模块',
      description: '底盘控制',
      icon: <Settings size={20} />,
      critical: true
    }
  ];

  const toggleModule = (moduleId: string) => {
    if (moduleStates[moduleId as keyof typeof moduleStates]) {
      // 关闭模块前确认
      setShowConfirmDialog(moduleId);
    } else {
      // 直接开启模块
      setModuleStates(prev => ({
        ...prev,
        [moduleId]: true
      }));
    }
  };

  const confirmToggle = (moduleId: string) => {
    setModuleStates(prev => ({
      ...prev,
      [moduleId]: !prev[moduleId as keyof typeof moduleStates]
    }));
    setShowConfirmDialog(null);
  };

  const toggleAutonomousMode = () => {
    if (moduleStates.autonomousMode) {
      setShowConfirmDialog('autonomous');
    } else {
      setModuleStates(prev => ({
        ...prev,
        autonomousMode: true
      }));
    }
  };

  const getModuleStatus = (moduleId: string) => {
    const isEnabled = moduleStates[moduleId as keyof typeof moduleStates];
    const moduleStatusData = moduleStatus[moduleId as keyof typeof moduleStatus];
    
    if (!isEnabled) {
      return { status: 'offline', color: 'text-gray-400', bgColor: 'bg-gray-600/20' };
    }
    
    switch (moduleStatusData) {
      case 'online':
        return { status: 'online', color: 'text-success-400', bgColor: 'bg-success-600/20' };
      case 'warning':
        return { status: 'warning', color: 'text-warning-400', bgColor: 'bg-warning-600/20' };
      case 'offline':
        return { status: 'offline', color: 'text-danger-400', bgColor: 'bg-danger-600/20' };
      default:
        return { status: 'unknown', color: 'text-gray-400', bgColor: 'bg-gray-600/20' };
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'online':
        return <CheckCircle size={16} className="text-success-400" />;
      case 'warning':
        return <AlertTriangle size={16} className="text-warning-400" />;
      case 'offline':
        return <XCircle size={16} className="text-danger-400" />;
      default:
        return <WifiOff size={16} className="text-gray-400" />;
    }
  };

  return (
    <div className="control-panel">
      <h3 className="text-lg font-semibold mb-4 text-white">模块开关配置</h3>

      {/* 一键自动驾驶开关 */}
      <div className="mb-6">
        <div className={`p-4 rounded-lg border-2 ${
          moduleStates.autonomousMode 
            ? 'border-success-500/30 bg-success-600/20' 
            : 'border-gray-500/30 bg-gray-600/20'
        }`}>
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-3">
              <Power size={24} className={moduleStates.autonomousMode ? 'text-success-400' : 'text-gray-400'} />
              <div>
                <h4 className="text-lg font-medium text-white">自动驾驶模式</h4>
                <p className="text-sm text-gray-400">一键开启/关闭自动驾驶系统</p>
              </div>
            </div>
            <button
              onClick={toggleAutonomousMode}
              className={`w-12 h-6 rounded-full transition-colors ${
                moduleStates.autonomousMode ? 'bg-success-500' : 'bg-gray-600'
              }`}
            >
              <div className={`w-5 h-5 bg-white rounded-full transition-transform ${
                moduleStates.autonomousMode ? 'translate-x-6' : 'translate-x-0.5'
              }`} />
            </button>
          </div>
          <div className="text-xs text-gray-400">
            状态: {moduleStates.autonomousMode ? '已激活' : '已关闭'}
          </div>
        </div>
      </div>

      {/* 模块开关列表 */}
      <div className="space-y-3">
        {modules.map((module) => {
          const moduleStatus = getModuleStatus(module.id);
          const isEnabled = moduleStates[module.id as keyof typeof moduleStates];
          
          return (
            <div
              key={module.id}
              className={`p-3 rounded-lg border ${moduleStatus.bgColor} ${
                isEnabled ? 'border-opacity-30' : 'border-gray-500/30'
              }`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className={isEnabled ? 'text-primary-400' : 'text-gray-400'}>
                    {module.icon}
                  </div>
                  <div>
                    <h5 className="text-sm font-medium text-white">{module.name}</h5>
                    <p className="text-xs text-gray-400">{module.description}</p>
                  </div>
                </div>
                
                <div className="flex items-center gap-3">
                  {/* 状态指示器 */}
                  <div className="flex items-center gap-1">
                    {getStatusIcon(moduleStatus.status)}
                    <span className={`text-xs ${moduleStatus.color}`}>
                      {moduleStatus.status === 'online' ? '在线' :
                       moduleStatus.status === 'warning' ? '警告' :
                       moduleStatus.status === 'offline' ? '离线' : '未知'}
                    </span>
                  </div>
                  
                  {/* 开关按钮 */}
                  <button
                    onClick={() => toggleModule(module.id)}
                    className={`w-10 h-5 rounded-full transition-colors ${
                      isEnabled ? 'bg-primary-500' : 'bg-gray-600'
                    }`}
                  >
                    <div className={`w-4 h-4 bg-white rounded-full transition-transform ${
                      isEnabled ? 'translate-x-5' : 'translate-x-0.5'
                    }`} />
                  </button>
                </div>
              </div>
              
              {/* 关键模块警告 */}
              {module.critical && !isEnabled && (
                <div className="mt-2 p-2 bg-danger-600/20 border border-danger-500/30 rounded text-xs text-danger-400">
                  ⚠️ 关键模块已关闭，可能影响系统安全
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* 确认对话框 */}
      {showConfirmDialog && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-gray-800 p-6 rounded-lg border border-gray-600 max-w-md mx-4">
            <div className="flex items-center gap-3 mb-4">
              <AlertTriangle size={24} className="text-warning-400" />
              <h3 className="text-lg font-medium text-white">确认操作</h3>
            </div>
            <p className="text-gray-300 mb-6">
              {showConfirmDialog === 'autonomous' 
                ? '关闭自动驾驶模式将切换到手动驾驶，确定要继续吗？'
                : `关闭${modules.find(m => m.id === showConfirmDialog)?.name}模块可能影响系统功能，确定要继续吗？`
              }
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowConfirmDialog(null)}
                className="flex-1 hmi-button-secondary"
              >
                取消
              </button>
              <button
                onClick={() => confirmToggle(showConfirmDialog)}
                className="flex-1 hmi-button-danger"
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 系统状态摘要 */}
      <div className="mt-6 p-3 bg-gray-800/50 rounded-lg">
        <h4 className="text-sm font-medium text-gray-300 mb-2">系统状态摘要</h4>
        <div className="grid grid-cols-2 gap-2 text-xs text-gray-400">
          <div>自动驾驶: {moduleStates.autonomousMode ? '已激活' : '已关闭'}</div>
          <div>在线模块: {Object.values(moduleStates).filter(Boolean).length - 1}/{modules.length}</div>
          <div>关键模块: {modules.filter(m => moduleStates[m.id as keyof typeof moduleStates]).length}/{modules.length}</div>
          <div>系统状态: {moduleStates.autonomousMode ? '运行中' : '待机'}</div>
        </div>
      </div>
    </div>
  );
};

export default ModuleControlPanel;
